<template>
  <div class="user-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <el-table :data="userList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'danger' : 'success'">
            {{ row.status === 0 ? '禁用' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button 
            :type="row.status === 0 ? 'success' : 'danger'"
            size="small" 
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 0 ? '启用' : '禁用' }}
          </el-button>
          <el-button type="warning" size="small" @click="handleResetPwd(row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="page.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChanxge"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, saveUser, updateUserStatus, resetUserPassword } from '@/api/user'

// 搜索表单：用于用户列表的筛选条件
const searchForm = reactive({
  email: ''     // 只保留邮箱搜索
})

// 分页参数：控制数据分页显示
const page = reactive({
  current: 1,    // 当前页码
  size: 10,      // 每页显示条数
  total: 0       // 总记录数
})

// 数据列表：存储用户列表
const userList = ref([])      // 用户列表数据

// 表单相关：控制对话框和表单状态
const dialogVisible = ref(false)  // 对话框显示状态
const dialogTitle = ref('添加用户')  // 对话框标题
const formRef = ref(null)         // 表单引用，用于验证
const form = reactive({
  id: null,
  username: '',
  password: '',
  email: '',
  phone: ''
})

// 表单验证规则：定义各字段的验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 获取用户列表：从API获取用户数据并处理
const fetchUserList = async () => {
  try {
    const params = {
      Page: page.current,
      PageSize: page.size,
      Email: searchForm.email
    }
    const { data } = await getUserList(params)
    console.log('API返回的用户数据：', data.list)
    console.log('第一个用户的状态：', data.list[0]?.status, '类型：', typeof data.list[0]?.status)
    userList.value = data.list
    page.total = data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 搜索处理：触发列表刷新
const handleSearch = () => {
  page.current = 1  // 重置到第一页
  fetchUserList()   // 重新获取列表数据
}

// 重置搜索：重置所有搜索条件
const resetSearch = () => {
  searchForm.email = ''
  handleSearch()
}

// 分页大小变化处理
const handleSizeChange = (val) => {
  page.size = val
  fetchUserList()
}

// 页码变化处理
const handleCurrentChange = (val) => {
  page.current = val
  fetchUserList()
}

// 编辑用户：填充表单数据并显示对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 切换用户状态：启用/禁用用户
const handleToggleStatus = (row) => {
  const action = row.status === 0 ? '启用' : '禁用'
  const newStatus = row.status === 0 ? 1 : 0
  
  ElMessageBox.confirm(`确认${action}该用户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateUserStatus({"id":row.id}, newStatus)
      ElMessage.success(`${action}成功`)
      fetchUserList() // 刷新列表
    } catch (error) {
      ElMessage.error(`${action}失败：${error.message}`)
    }
  }).catch(() => {
    // 取消操作，不做处理
  })
}

// 重置密码：确认并调用重置密码API
const handleResetPwd = (row) => {
  ElMessageBox.confirm('确认重置该用户的密码吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await resetUserPassword({id:row.id})
      ElMessage.success('重置密码成功')
    } catch (error) {
      ElMessage.error('重置密码失败')
    }
  })
}

// 表单提交处理
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 使用 saveUser 处理新增和编辑
        await saveUser({
          id: form.id,
          username: form.username,
          password: form.password,
          email: form.email,
          phone: form.phone
        })
        ElMessage.success(form.id ? '更新成功' : '创建成功')
        dialogVisible.value = false
        resetForm()
        fetchUserList()
      } catch (error) {
        ElMessage.error(form.id ? '更新失败' : '创建失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    username: '',
    password: '',
    email: '',
    phone: ''
  })
}

// 添加用户按钮处理函数
const handleAdd = () => {
  dialogTitle.value = '添加用户'
  resetForm()
  dialogVisible.value = true
}

// 使用 onMounted 钩子函数初始化数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
/* 用户管理页面容器 */
.user-container {
  padding: 20px;
}

/* 搜索栏：底部留出间距 */
.search-bar {
  margin-bottom: 20px;
}

/* 操作栏：底部留出间距 */
.operation-bar {
  margin-bottom: 20px;
}

/* 分页容器：顶部留出间距，右对齐 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 